<template>
  <div class="image-upload">
    <el-upload
      :action="uploadUrl"
      :headers="uploadHeaders"
      :data="uploadData"
      :name="uploadFileName"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :limit="limit"
      :multiple="multiple"
      list-type="picture-card"
      :class="{ 'hide-upload': fileList.length >= limit }"
      :disabled="loading"
    >
      <el-icon><Plus /></el-icon>
      <template #tip>
        <div class="el-upload__tip">
          支持 JPG、PNG、GIF 格式，单张图片不超过5MB
        </div>
      </template>
    </el-upload>
    
    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="800px">
      <img :src="previewImageUrl" style="width: 100%" alt="预览图片" />
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import { getApiBaseUrl } from '../utils/apiConfig'

export default {
  name: 'ImageUpload',
  components: {
    Plus
  },
  props: {
    // 上传类型：'attraction', 'avatar', 'post'
    uploadType: {
      type: String,
      required: true,
      validator: (value) => ['attraction', 'avatar', 'post'].includes(value)
    },
    // 关联ID（景点ID或动态ID）
    relatedId: {
      type: [Number, String],
      default: null
    },
    // 最大上传数量
    limit: {
      type: Number,
      default: 9
    },
    // 是否支持多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 已上传的图片列表
    modelValue: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'success', 'error'],
  setup(props, { emit }) {
    const store = useStore()
    const loading = ref(false)
    const previewVisible = ref(false)
    const previewImageUrl = ref('')
    
    const fileList = computed(() => {
      return props.modelValue.map((item, index) => ({
        uid: item.id || index,
        name: item.name || `image_${index}.jpg`,
        url: item.url || item.image,
        status: 'success'
      }))
    })
    
    const uploadUrl = computed(() => {
      const baseUrl = getApiBaseUrl()
      
      switch (props.uploadType) {
        case 'attraction':
          if (!props.relatedId) {
            console.error('景点图片上传需要提供relatedId')
            return ''
          }
          return `${baseUrl}/api/attractions/${props.relatedId}/upload_image/`
        case 'avatar':
          return `${baseUrl}/api/users/upload_avatar/`
        case 'post':
          if (!props.relatedId) {
            console.error('动态图片上传需要提供relatedId')
            return ''
          }
          return `${baseUrl}/api/social/posts/${props.relatedId}/upload_images/`
        default:
          return ''
      }
    })
    
    const uploadHeaders = computed(() => {
      const token = store.state.token || localStorage.getItem('token')
      return {
        'Authorization': token ? `Token ${token}` : ''
      }
    })
    
    const uploadData = computed(() => {
      if (props.uploadType === 'attraction') {
        return {
          is_primary: false
        }
      }
      return {}
    })
    
    const uploadFileName = computed(() => {
      // 根据上传类型设置文件字段名
      if (props.uploadType === 'avatar') {
        return 'avatar'
      } else if (props.uploadType === 'post') {
        return 'images'
      } else {
        return 'image'
      }
    })
    
    const beforeUpload = (file) => {
      // 检查文件类型
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
      }
      
      // 检查文件大小（5MB）
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB！')
        return false
      }
      
      return true
    }
    
    const handleSuccess = (response, file) => {
      loading.value = false
      
      if (response.error) {
        ElMessage.error(response.error)
        emit('error', response.error)
        return
      }
      
      ElMessage.success(response.message || '上传成功')
      
      // 更新文件列表
      let newImages = []
      if (props.uploadType === 'avatar') {
        // 头像上传返回用户信息
        if (response.user && response.user.avatar) {
          newImages = [{
            id: 'avatar',
            url: response.user.avatar,
            name: 'avatar.jpg'
          }]
        }
      } else if (props.uploadType === 'post' && response.images) {
        // 动态图片上传返回图片数组
        newImages = response.images.map(img => ({
          id: img.id,
          url: img.image,
          name: `image_${img.id}.jpg`
        }))
      } else {
        // 景点图片上传
        newImages = [{
          id: response.id,
          url: response.image,
          name: file.name
        }]
      }
      
      const updatedList = [...props.modelValue, ...newImages]
      emit('update:modelValue', updatedList)
      emit('success', response, file)
    }
    
    // eslint-disable-next-line no-unused-vars
    const handleError = (error, file) => {
      loading.value = false
      const errorMsg = error.message || '上传失败，请重试'
      ElMessage.error(errorMsg)
      emit('error', error)
    }
    
    // eslint-disable-next-line no-unused-vars
    const handleProgress = (event, file) => {
      loading.value = true
    }
    
    return {
      loading,
      previewVisible,
      previewImageUrl,
      fileList,
      uploadUrl,
      uploadHeaders,
      uploadData,
      uploadFileName,
      beforeUpload,
      handleSuccess,
      handleError,
      handleProgress
    }
  }
}
</script>

<style scoped>
.image-upload {
  width: 100%;
}

.hide-upload :deep(.el-upload--picture-card) {
  display: none;
}

:deep(.el-upload--picture-card) {
  width: 148px;
  height: 148px;
  line-height: 148px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 148px;
  height: 148px;
}

.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 7px;
  text-align: center;
}
</style>

